importClass(java.util.HashSet);
importClass(java.util.List);
importClass(java.util.Map);
importClass(java.util.ArrayList);
importPackage(Packages.org.bukkit);
importPackage(Packages.java.io);
importPackage(Packages.java.awt);
importPackage(Packages.javax.imageio);
importPackage(Packages.com.sk89q.worldedit);
importPackage(Packages.com.sk89q.worldedit.schematic);
importPackage(Packages.com.sk89q.worldedit.blocks);
importPackage(Packages.com.sk89q.worldguard.bukkit);
importPackage(Packages.com.sk89q.worldguard.bukkit.commands);

var sess = context.remember();
var snapshotname="2014-05-07.zip";
var pl = Bukkit.getPlayer(player.getName());

function genChunksAround(w, rg){
  var v1 = rg.getMinimumPoint();
  var v2 = rg.getMaximumPoint();
  var c1 = w.getChunkAt(new org.bukkit.Location(w,v1.getX(),v1.getY(),v1.getZ()));
  var c2 = w.getChunkAt(new org.bukkit.Location(w,v2.getX(),v2.getY(),v2.getZ()));
  var chunks = new ArrayList();
  Bukkit.getLogger().info("Generating chunks: "+rg.getId());
  for(x = c1.getX()-1; x<=c2.getX()+1 ; x++){
    for(z = c1.getZ()-1; z<=c2.getZ()+1 ; z++){
      var c = w.getChunkAt(x,z);
      c.load(true);
      chunks.add(c);
      Bukkit.getLogger().info(""+c+" generated");
    }
  }
  return chunks;
}

rgcount=1;

for(var worlds = Bukkit.getWorlds().iterator(); worlds.hasNext();){
  var w = worlds.next();
  var rm = WGBukkit.getRegionManager(w);
  var regions = rm.getRegions().keySet().toArray();
  pl.performCommand("eworld "+w.getName());
  pl.performCommand("snap use "+w.getName()+"/"+snapshotname);
  java.lang.Thread.sleep(5000);
  for(var rn=0; rn<regions.length; rn++){
    r = rm.getRegion(regions[rn]);
    if(r.volume()<10000000){
      player.print("now restoring: "+r.getId());
      var ch = genChunksAround(w, r);
      pl.performCommand("rg select "+r.getId());
      Bukkit.getLogger().info("Restoring: "+r.getId());
      pl.performCommand("/restore");
      Bukkit.getLogger().info("Restored "+r.getId());
      for(var ci=ch.iterator(); ci.hasNext();){
        chunk = ci.next();
        w.unloadChunkRequest(chunk.getX(),chunk.getZ(),true);
      }
      if(rgcount==50){
        w.save();
        Bukkit.getLogger().info("World "+w.getName()+" saved");
        java.lang.Thread.sleep(500);
        rgcount=0;
      }
      sess = context.remember();
      rgcount++;
    }
  }
}

